#include "Common.hpp"
#include <iostream>



//地址对象，负责ip 端口 _struct sockaddr     网络/主机字节序、字符串/二进制ip之间的转换，为了使得服务端与该部分解耦，让服务端只负责建立连接
class InetAddr
{
public:
    //无参构造
    InetAddr(){}

    //从网络中获取的数据 转为 本地数据
    InetAddr(struct sockaddr_in& addr)
    {
        GetAddr(addr);
    }

    //将端口的主机字节序转网络字节序    
    InetAddr(uint16_t port)
        :_port(port)
    {
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_addr.s_addr = INADDR_ANY;
        _addr.sin_port = htons(_port);
    }

    //将 ip 和 端口号 转为网络字节序
    InetAddr(std::string& ip, uint16_t port)
        :_ip(ip),
        _port(port)
    {
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(_port);
        inet_pton(AF_INET, _ip.c_str(), &_addr.sin_addr);
    }
    
    void GetAddr(struct sockaddr_in& addr)
    {
        _addr = addr;
        char inbuffer[64];
        inet_ntop(AF_INET,&_addr.sin_addr, inbuffer,sizeof(inbuffer));
        _ip = inbuffer;
        _port = ntohs(_addr.sin_port);
    }

    std::string Ip(){   return _ip; }
    uint16_t Port(){    return _port; }
    struct sockaddr_in Addr() {  return _addr; }
    struct sockaddr* AddrPtr() {  return CONV(_addr); }
    socklen_t Addrlen() { return sizeof(_addr); }
    std::string AddrMessage(){  return _ip + ": " + std::to_string(_port); }

    bool operator=(struct InetAddr& addr)
    {
        return _ip == addr._ip && _port == addr._port;
    }

private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _addr;
};